Function.RegisterNamespace("System.IO.FileStrategy");

System.IO.FileStrategy.Xhr=function(){
    // IFileStrategy Members
    this.DeleteFile=function(path){
        var transport=getTransport();
        if(transport.overrideMimeType)transport.overrideMimeType("text/plain");
        transport.open('DELETE',getTarget(),false);
        transport.send(String.Format("path={0}",encodeURIComponent(System.IO.Path.GetFullPath(path))));
        if(!transport.status||transport.status==200)return transport.responseText;
        return null;
    };

    this.Exists=function(path){
        var transport=getTransport();
        transport.open('HEAD',String.Format("{0}?type=file&path={1}",getTarget(),encodeURIComponent(System.IO.Path.GetFullPath(path))),false);
        transport.send();
        if(!transport.status||transport.status==200)return true;
        return false;
    };

    this.GetFile=function(path){
        var transport=getTransport();
        if(transport.overrideMimeType)transport.overrideMimeType("text/plain");
        transport.open('GET',String.Format("{0}?type=file&path={1}",getTarget(),encodeURIComponent(System.IO.Path.GetFullPath(path))),false);
        transport.send();
        if(!transport.status||transport.status==200)return transport.responseText;
        return null;
    };

    this.SaveFile=function(path,text){
        var transport=getTransport();
        if(transport.overrideMimeType)transport.overrideMimeType("text/plain");
        transport.open('POST',getTarget(),false);
        transport.send(String.Format("type=file&path={0}&content={1}",encodeURIComponent(System.IO.Path.GetFullPath(path)),encodeURIComponent(text)||''));
        if(!transport.status||transport.status==200)return transport.responseText;
        return null;
    };

    // IStrategySpecification Members
    this.IsSatisfiedBy=function(candidate){
        return getTransport()!=null;
    };

    // Private Methods
    function getTarget(){
        if(!System.IO.FileStrategy.Xhr.ResourceUri)throw new Error("'System.IO.FileStrategy.Xhr.ResourceUri' must be set before invoking IFileStrategy methods.");
        return System.IO.FileStrategy.Xhr.ResourceUri;
    }

    function getTransport(){
        if(typeof(XMLHttpRequest)!='undefined')return new XMLHttpRequest();
        if(typeof(ActiveXObject)!='undefined')return new ActiveXObject('Microsoft.XMLHTTP');
        return null;
    }
};

System.IO.FileStrategy.Xhr.Implement(System.IO.FileStrategy.IFileStrategy,'System.IO.FileStrategy.Xhr');
System.IO.FileStrategy.Xhr.Implement(System.Script.Strategy.IStrategySpecification,'System.IO.FileStrategy.Xhr');

System.IO.File.Strategies.Add(System.IO.FileStrategy.Xhr);